/*******************************************************************************
 * Copyright (c) 2014-2015 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *	IBM Zurich Research Lab - initial API, implementation and documentation
 *******************************************************************************/

#include "lmic.h"
#include "debug.h"

//////////////////////////////////////////////////
// CONFIGURATION (FOR APPLICATION CALLBACKS BELOW)
//////////////////////////////////////////////////

// application router ID (LSBF)
static const uint8_t APPEUI[8]  = { 0x02, 0x00, 0x00, 0x00, 0x00, 0xEE, 0xFF, 0xC0 };

// unique device ID (LSBF)
static const uint8_t DEVEUI[8]  = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

// device-specific AES key (derived from device EUI)
static const uint8_t DEVKEY[16] = { 0xAB, 0x89, 0xEF, 0xCD, 0x23, 0x01, 0x67, 0x45, 0x54, 0x76, 0x10, 0x32, 0xDC, 0xFE, 0x98, 0xBA };


//////////////////////////////////////////////////
// APPLICATION CALLBACKS
//////////////////////////////////////////////////

// provide application router ID (8 bytes, LSBF)
void os_getArtEui (uint8_t* buf)	{	memcpy(buf, APPEUI, 8);		}
// provide device ID (8 bytes, LSBF)
void os_getDevEui (uint8_t* buf)	{	memcpy(buf, DEVEUI, 8);		}
// provide device key (16 bytes)
void os_getDevKey (uint8_t * buf)	{	memcpy(buf, DEVKEY, 16);	}

//////////////////////////////////////////////////
// MAIN - INITIALIZATION AND STARTUP
//////////////////////////////////////////////////

// initial job
static void initfunc (osjob_t* j)
{
	LMIC_reset();			// reset MAC state
	LMIC_startJoining();	// start joining
	// init done - onEvent() callback will be invoked...
}

// application entry point
int main ()
{
	osjob_t initjob;

	os_init();		// initialize runtime env
	debug_init();	// initialize debug library
					// setup initial job
	os_setCallback(&initjob, initfunc);
	os_runloop();	// execute scheduled jobs and events
	// (not reached)
	return 0;
}

//////////////////////////////////////////////////
// LMIC EVENT CALLBACK
//////////////////////////////////////////////////

void onEvent (ev_t ev) {
	debug_event(ev);

	switch(ev)
	{
	// network joined, session established
	case EV_JOINED:
		// enable tracking mode, start scanning...
		LMIC_enableTracking(0);
		debug_str("SCANNING...\r\n");
		break;

	// beacon found by scanning
	case EV_BEACON_FOUND:
		// switch LEN on
		debug_led(1);
		break;

	// beacon tracked at expected time
	case EV_BEACON_TRACKED:
		debug_val("GPS time = ", LMIC.bcninfo.time);
		// switch LEN on
		debug_led(1);
		break;

	// beacon missed at expected time
	case EV_BEACON_MISSED:
		// switch LEN off
		debug_led(0);
		break;

	default:
		break;
	}
}
